<template>
  <div class="chat-messages" >    
    <!-- 加载更多提示 -->
    <div v-if="isLoading" class="loading-more">
      <div class="loading-spinner"></div>
      <span>加载历史消息...</span>
    </div>
    
    <div v-for="(msg, index) in messages" :key="msg.id || index" class="mb-4">
      <div :class="[
        'message-container',
        msg.sender === 'user' ? 'user-message' : 'assistant-message'
      ]">
        <!-- AI头像 - 仅在AI消息时显示在左侧 -->
        <div v-if="msg.sender === 'assistant'" class="message-avatar">
          <div class="assistant-avatar">
            <img v-if="props.appDetail.poster" :src="props.appDetail.poster" alt="AI" class="avatar-image">
            <span v-else>AI</span>
          </div>
        </div>
        
        <div class="message-content" :class="msg.sender === 'user' ? 'user-content' : 'assistant-content'">
          <div v-if="msg.sender === 'user'" class="message-text user-text">
            {{ msg.text }}
          </div>
          <div v-else class="message-text assistant-text ">
            <div v-if="msg.isStreaming" class="streaming-indicator">
              <span class="typing-dot"></span>
              <span class="typing-dot"></span>
              <span class="typing-dot"></span>
            </div>
            <div v-html="renderMarkdownWithCopyButton(msg.text)" class="markdown-body"></div>
          </div>
          <div class="message-time" :class="msg.sender === 'user' ? 'text-right' : ''">
            {{ formatTime(msg.timestamp) }}
          </div>
        </div>
        
        <!-- 用户头像 - 仅在用户消息时显示在右侧 -->
        <div v-if="msg.sender === 'user'" class="message-avatar">
          <div class="user-avatar">
            <img v-if="userInfo?.avatar" :src="userInfo.avatar" alt="User" class="avatar-image">
            <span v-else>U</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import { useChatStore } from '~/stores/chat'
import 'github-markdown-css/github-markdown-light.css' // 导入GitHub风格的Markdown主题
import WelcomeTip from '~/components/chat/WelcomeTip.vue'

// 获取聊天store
const chatStore = useChatStore()
const messagesContainer = ref(null)
const isLoading = computed(() => chatStore.isLoadingHistory)
const scrollPosition = ref(0)
const isLoadingMore = ref(false)
const showScrollToBottom = ref(false)

// 获取用户信息
const { data: userInfo } = useAuth()

// 配置marked选项
marked.setOptions({
  gfm: true, // 启用GitHub风格的Markdown
  breaks: true, // 将回车符转换为<br>
  headerIds: true, // 为标题添加id属性
  mangle: false, // 不对链接进行编码
  pedantic: false, // 更宽松的解析
  smartLists: true, // 使用更智能的列表行为
  smartypants: false, // 使用更智能的标点符号
  highlight: function(code, lang) {
    // 如果需要代码高亮，可以在这里添加代码高亮库的调用
    return code;
  }
});

// 注册自定义renderer，用于添加复制按钮
const renderer = new marked.Renderer();

// 重写代码块的渲染方法，添加复制按钮
renderer.code = function(code, language) {
  const langClass = language ? ` class="language-${language}"` : '';
  const codeId = `code-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  return `
    <div class="code-block-wrapper">
      <div class="code-header">
        <span class="code-language">${language || 'text'}</span>
        <button class="copy-code-btn" onclick="copyCode('${codeId}')">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1-2 2v1"></path>
          </svg>
        </button>
      </div>
      <pre><code id="${codeId}"${langClass}>${code.text}</code></pre>
    </div>
  `;
};

marked.use({ renderer });

// 添加复制代码函数到window对象
onMounted(() => {
  if (window) {
    window.copyCode = (codeId) => {
      const codeElement = document.getElementById(codeId);
      if (codeElement) {
        const textToCopy = codeElement.textContent;
        navigator.clipboard.writeText(textToCopy).then(() => {
          // 可以添加复制成功的反馈
          const button = document.querySelector(`#${codeId}`).parentNode.previousElementSibling.querySelector('.copy-code-btn');
          if (button) {
            // 保存原始SVG内容
            const originalInnerHTML = button.innerHTML;
            // 替换为成功图标
            button.innerHTML = `
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M20 6L9 17l-5-5"></path>
              </svg>
            `;
            // 2秒后恢复原样
            setTimeout(() => {
              button.innerHTML = originalInnerHTML;
            }, 2000);
          }
        }).catch(err => {
          console.error('Failed to copy text: ', err);
        });
      }
    };
  }
});

const props = defineProps({
  messages: {
    type: Array,
    default: () => []
  },
  appDetail:{
    type:Object,
    default:()=>({
      welcomeTip:"",
      poster:""
    })
  }
})

// 带复制按钮的Markdown渲染
const renderMarkdownWithCopyButton = (text) => {
  if (!text) return '';
  try {
    // 使用marked渲染Markdown，并使用DOMPurify清理HTML
    const html = marked.parse(text);
    return DOMPurify.sanitize(html, { ADD_ATTR: ['onclick'] }); // 允许onclick属性
  } catch (error) {
    console.error('Error rendering markdown:', error);
    return text;
  }
};

// 渲染Markdown内容
const renderMarkdown = (text) => {
  if (!text) return ''
  try {
    // 使用marked渲染Markdown，并使用DOMPurify清理HTML
    const html = marked.parse(text)
    return DOMPurify.sanitize(html)
  } catch (error) {
    console.error('Error rendering markdown:', error)
    return text
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  
  return `${hours}:${minutes}`
}






onMounted(() => {
  // 初始加载时滚动到底部
  nextTick(() => {
  });
});
</script>

<style lang="scss" scoped>
.chat-messages {
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0.75rem; /* 减少整体内边距 */
  box-sizing: border-box;
  padding-bottom: 100px;
}



.loading-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 10px;
  color: #666;
  font-size: 14px;
  
  .loading-spinner {
    width: 16px;
    height: 16px;
    border: 2px solid #f3f3f3;
    border-top: 2px solid #3498db;
    border-radius: 50%;
    margin-right: 8px;
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.message-container {
  display: flex;
  margin-bottom: 0.75rem; /* 减少消息之间的间距 */
}

/* 消息容器样式 */
.user-message {
  justify-content: flex-end;
  
  .message-avatar {
    margin-left: 8px; /* 减少头像与消息内容的间距 */
  }
}

.assistant-message {
  justify-content: flex-start;
  
  .message-avatar {
    margin-right: 8px; /* 减少头像与消息内容的间距 */
  }
}

.message-avatar {
  flex-shrink: 0;
}

.user-avatar, .assistant-avatar {
  width: 32px; /* 头像大小 */
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  overflow: hidden; /* 确保图片不溢出容器 */
  
  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover; /* 确保图片填充整个容器，可能会裁剪 */
  }
}

.user-avatar {
  background-color: #e9f5ff;
  color: #1890ff;
}

.assistant-avatar {
  background-color: #f0f9eb;
  color: #67c23a;
}

.message-content {
  max-width: 100%; /* 增加一点宽度利用空间 */
}

/* 用户消息的内容靠右对齐 */
.user-content {
  text-align: right;
}

/* AI消息的内容靠左对齐 */
.assistant-content {
  text-align: left;
  background-color: #f7f7f7;
  padding: 10px;
}

.message-text {
  display: inline-block;
  padding: 8px 12px; /* 减少文本内部的内边距 */
  box-sizing: border-box;
  border-radius: 8px;
  white-space: pre-wrap;
  word-break: break-word;
  text-align: left; /* 文本内容始终左对齐 */
}

.user-text {
  background-color: #1890ff;
  color: white;
  border-top-right-radius: 2px;
}

.assistant-text {
  background-color: #f7f7f7;
  color: #333;
  border-top-left-radius: 2px;
  /* Markdown内容样式调整 */
  padding-bottom: 4px; /* 减少底部边距 */
}



.message-time {
  font-size: 11px; /* 缩小字体 */
  color: #999;
  margin-top: 2px; /* 减少与消息文本的间距 */
}

.text-right {
  text-align: right;
}

.streaming-indicator {
  display: inline-flex;
  align-items: center;
  margin-bottom: 4px; /* 减少指示器的底部间距 */
  
  .typing-dot {
    width: 6px; /* 缩小点的大小 */
    height: 6px;
    border-radius: 50%;
    background-color: #999;
    margin-right: 3px;
    animation: typing 1.4s infinite ease-in-out;
    
    &:nth-child(1) {
      animation-delay: 0s;
    }
    
    &:nth-child(2) {
      animation-delay: 0.2s;
    }
    
    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.6;
  }
  30% {
    transform: translateY(-3px); /* 减少动画幅度 */
    opacity: 1;
  }
}
</style>

<style>


</style>